#!/bin/sh

K8S_AZ_LOCATION="${K8S_AZ_LOCATION:-northeurope}"
K8S_AZ_RESOURCE_GROUP="${K8S_AZ_RESOURCE_GROUP:-stackgres-e2e}"
K8S_AZ_K8S_NAME="${K8S_AZ_K8S_NAME:-stackgres}"
K8S_VERSION="${K8S_VERSION:-1.27}"
K8S_AZ_NODE_SIZE="${K8S_AZ_NODE_SIZE:-Standard_A2m_v2}"
K8S_AZ_NODE_COUNT="${K8S_AZ_NODE_COUNT:-4}"
K8S_AZ_REGISTRY="${K8S_AZ_REGISTRY:-stackgrese2e}"

export E2E_USE_INTERMIDIATE_PRIVATE_REPO="${E2E_USE_INTERMIDIATE_PRIVATE_REPO:-true}"
export E2E_OPERATOR_PULL_POLICY=Always

get_k8s_env_version() {
  echo "az version $(az version 2>/dev/null | grep -F '"azure-cli"' | cut -d '"' -f 4)"
  echo
}

set_up_resource_group(){
  RS_EXISTS="$(az group exists --name "$K8S_AZ_RESOURCE_GROUP")"
  if [ "$RS_EXISTS" = true ]
  then
    echo "Deleting previous resource group"
    az group delete --name "$K8S_AZ_RESOURCE_GROUP" --yes
  fi
  echo "creating resource group $K8S_AZ_RESOURCE_GROUP"

  az group create --name "$K8S_AZ_RESOURCE_GROUP" --location "$K8S_AZ_LOCATION"
}

reset_k8s() {
  set_up_resource_group

  if [ -z "$SP_APP_ID" ] || [ -z "$SP_PASSWORD" ]
  then
    az aks create --name "$K8S_AZ_K8S_NAME" --resource-group "$K8S_AZ_RESOURCE_GROUP" \
      --kubernetes-version "$K8S_VERSION" --node-count "$K8S_AZ_NODE_COUNT" \
      --node-vm-size "$K8S_AZ_NODE_SIZE" \
      --generate-ssh-keys \
      --enable-node-public-ip
  else
    az aks create --name "$K8S_AZ_K8S_NAME" --resource-group "$K8S_AZ_RESOURCE_GROUP" \
      --kubernetes-version "$K8S_VERSION" --node-count "$K8S_AZ_NODE_COUNT" \
      --node-vm-size "$K8S_AZ_NODE_SIZE" \
      --service-principal "$SP_APP_ID" \
      --client-secret "$SP_PASSWORD" \
      --generate-ssh-keys \
      --enable-node-public-ip
  fi    

  az aks get-credentials --name "$K8S_AZ_K8S_NAME" --resource-group "$K8S_AZ_RESOURCE_GROUP" --overwrite-existing

  az storage account create --name "$K8S_AZ_K8S_NAME" -g "$K8S_AZ_RESOURCE_GROUP" --sku Standard_LRS
}

reuse_k8s() {
  if az aks show --name "$K8S_AZ_K8S_NAME" --resource-group "$K8S_AZ_RESOURCE_GROUP" > /dev/null
  then
    echo "Reusing aks environment $K8S_AZ_K8S_NAME"
    az aks get-credentials --name "$K8S_AZ_K8S_NAME" --resource-group "$K8S_AZ_RESOURCE_GROUP"
  else
    echo "Cannot resuse ask environment $AWS_NAME"
    exit 1
  fi
}

delete_k8s(){
   az group delete --name "$K8S_AZ_RESOURCE_GROUP" --yes
}

load_image_k8s() {
  echo "Cannot load images directly to k8s in a aks environment"
  exit 1
}

get_k8s_versions() {
  az aks get-versions --location "$K8S_AZ_LOCATION" | jq '.orchestrators[].orchestratorVersion' -r
}

get_expandable_storage_class_name() {
  kubectl get storageclasses.storage.k8s.io -o custom-columns=:.metadata.name,:.allowVolumeExpansion,:.provisioner \
    | awk '{ if ($2 == "true") { print } }' \
    | awk '{ if ($3 == "disk.csi.azure.com") { print } }' \
    | awk '{print $1}' \
    | head -n +1
}